import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Button, Badge, Switch, Space, Avatar } from 'antd';
import { 
  AppstoreOutlined,
  SettingOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  ThunderboltOutlined,
  SafetyOutlined,
  EnvironmentOutlined,
  CarOutlined,
  TeamOutlined,
  BulbOutlined
} from '@ant-design/icons';
import MainLayout from '../components/Layout/MainLayout';

interface SmartApp {
  id: string;
  name: string;
  description: string;
  icon: React.ReactNode;
  status: 'running' | 'stopped' | 'error';
  category: string;
  version: string;
  lastUpdate: string;
}

const AppsPage: React.FC = () => {
  const [apps, setApps] = useState<SmartApp[]>([]);
  const [loading, setLoading] = useState(true);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    loadApps();
  }, []);

  const loadApps = async () => {
    setLoading(true);
    try {
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      const mockApps: SmartApp[] = [
        {
          id: '1',
          name: '智能照明控制',
          description: '根据人员活动和光照条件自动调节照明',
          icon: <BulbOutlined style={{ fontSize: 32, color: '#faad14' }} />,
          status: 'running',
          category: '节能管理',
          version: 'v2.1.0',
          lastUpdate: '2024-01-15'
        },
        {
          id: '2',
          name: '智能停车引导',
          description: '实时显示空余车位，优化停车路径',
          icon: <CarOutlined style={{ fontSize: 32, color: '#1890ff' }} />,
          status: 'running',
          category: '交通管理',
          version: 'v1.8.2',
          lastUpdate: '2024-01-14'
        },
        {
          id: '3',
          name: '人员轨迹分析',
          description: '分析人员活动模式，优化空间布局',
          icon: <TeamOutlined style={{ fontSize: 32, color: '#52c41a' }} />,
          status: 'stopped',
          category: '数据分析',
          version: 'v1.5.1',
          lastUpdate: '2024-01-13'
        },
        {
          id: '4',
          name: '环境监测预警',
          description: '监测空气质量、温湿度等环境参数',
          icon: <EnvironmentOutlined style={{ fontSize: 32, color: '#13c2c2' }} />,
          status: 'running',
          category: '环境管理',
          version: 'v2.0.3',
          lastUpdate: '2024-01-15'
        },
        {
          id: '5',
          name: '安全巡检机器人',
          description: '自动巡检，异常情况实时报警',
          icon: <SafetyOutlined style={{ fontSize: 32, color: '#ff4d4f' }} />,
          status: 'error',
          category: '安全管理',
          version: 'v1.2.0',
          lastUpdate: '2024-01-12'
        },
        {
          id: '6',
          name: '能耗优化算法',
          description: '基于AI的能耗预测和优化建议',
          icon: <ThunderboltOutlined style={{ fontSize: 32, color: '#722ed1' }} />,
          status: 'running',
          category: '节能管理',
          version: 'v3.0.1',
          lastUpdate: '2024-01-15'
        },
      ];
      
      setApps(mockApps);
    } finally {
      setLoading(false);
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'running':
        return <Badge status="success" text="运行中" />;
      case 'stopped':
        return <Badge status="default" text="已停止" />;
      case 'error':
        return <Badge status="error" text="异常" />;
      default:
        return <Badge status="default" text="未知" />;
    }
  };

  const handleToggleApp = (appId: string, currentStatus: string) => {
    setApps(prevApps => 
      prevApps.map(app => 
        app.id === appId 
          ? { ...app, status: currentStatus === 'running' ? 'stopped' : 'running' }
          : app
      )
    );
  };

  if (!mounted) {
    return (
      <div style={{ padding: 20 }}>
        <div>加载中...</div>
      </div>
    );
  }

  const runningApps = apps.filter(app => app.status === 'running').length;
  const totalApps = apps.length;

  return (
    <MainLayout>
      <div>
        {/* 应用概览 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={8}>
            <Card>
              <div style={{ textAlign: 'center' }}>
                <AppstoreOutlined style={{ fontSize: 48, color: '#1890ff' }} />
                <h3 style={{ marginTop: 16, marginBottom: 8 }}>总应用数</h3>
                <span style={{ fontSize: 24, fontWeight: 'bold' }}>{totalApps}</span>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <div style={{ textAlign: 'center' }}>
                <PlayCircleOutlined style={{ fontSize: 48, color: '#52c41a' }} />
                <h3 style={{ marginTop: 16, marginBottom: 8 }}>运行中</h3>
                <span style={{ fontSize: 24, fontWeight: 'bold', color: '#52c41a' }}>
                  {runningApps}
                </span>
              </div>
            </Card>
          </Col>
          <Col span={8}>
            <Card>
              <div style={{ textAlign: 'center' }}>
                <SettingOutlined style={{ fontSize: 48, color: '#faad14' }} />
                <h3 style={{ marginTop: 16, marginBottom: 8 }}>系统负载</h3>
                <span style={{ fontSize: 24, fontWeight: 'bold', color: '#faad14' }}>
                  {Math.round((runningApps / totalApps) * 100)}%
                </span>
              </div>
            </Card>
          </Col>
        </Row>

        {/* 应用列表 */}
        <Row gutter={16}>
          {apps.map((app) => (
            <Col span={8} key={app.id} style={{ marginBottom: 16 }}>
              <Card
                hoverable
                actions={[
                  <Switch
                    key="toggle"
                    checked={app.status === 'running'}
                    onChange={() => handleToggleApp(app.id, app.status)}
                    disabled={app.status === 'error'}
                  />,
                  <Button type="link" icon={<SettingOutlined />} key="setting">
                    配置
                  </Button>,
                ]}
              >
                <Card.Meta
                  avatar={<Avatar size={64} icon={app.icon} />}
                  title={
                    <div>
                      <span>{app.name}</span>
                      <div style={{ float: 'right' }}>
                        {getStatusBadge(app.status)}
                      </div>
                    </div>
                  }
                  description={
                    <div>
                      <p style={{ margin: '8px 0', minHeight: 40 }}>{app.description}</p>
                      <Space direction="vertical" size={4} style={{ width: '100%' }}>
                        <div style={{ fontSize: 12, color: '#999' }}>
                          <span>分类：{app.category}</span>
                        </div>
                        <div style={{ fontSize: 12, color: '#999' }}>
                          <span>版本：{app.version}</span>
                        </div>
                        <div style={{ fontSize: 12, color: '#999' }}>
                          <span>更新：{app.lastUpdate}</span>
                        </div>
                      </Space>
                    </div>
                  }
                />
              </Card>
            </Col>
          ))}
        </Row>

        {/* 应用商店入口 */}
        <Card 
          style={{ marginTop: 24, textAlign: 'center' }}
          bodyStyle={{ padding: 40 }}
        >
          <AppstoreOutlined style={{ fontSize: 64, color: '#1890ff', marginBottom: 16 }} />
          <h2>发现更多智慧应用</h2>
          <p style={{ color: '#666', marginBottom: 24 }}>
            浏览应用商店，发现更多适合您园区的智慧化解决方案
          </p>
          <Button type="primary" size="large">
            访问应用商店
          </Button>
        </Card>
      </div>
    </MainLayout>
  );
};

export default AppsPage;